package com.chd.driversystem.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.chd.driversystem.activity.msgbean.NetMsg;
import com.chd.driversystem.domain.Evaluation;
import com.chd.driversystem.domain.Oil;
import com.chd.driversystem.domain.User;
import com.chd.driversystem.gen.BeanServer;
import com.chd.driversystem.util.network.HttpManager;
import com.chd.driversystem.util.network.bean.DayData;
import com.chd.driversystem.util.network.bean.MonthData;
import com.chd.driversystem.util.network.tools.HttpConstants;
import com.chd.driversystem.util.tools.LogUtil;
import com.chd.driversystem.util.tools.ResolveNetData;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 网络访问服务
 */
public class HttpService extends IntentService {

    private static final String TAG = "HttpService";

    public HttpService() {
        super("HttpService");
    }

    public static void startServiceLogin(Context context, String loginname, String password, boolean isManager) {
        Intent intent = new Intent(context, HttpService.class);
        intent.setAction(HttpConstants.ACTION_LOGIN);
        intent.putExtra(HttpConstants.EXTRA_PARAM1, loginname);
        intent.putExtra(HttpConstants.EXTRA_PARAM2, password);
        intent.putExtra(HttpConstants.EXTRA_PARAM3, isManager);
        context.startService(intent);
    }

    public static void startServiceSignUp(Context context, String loginname, String password, Integer pos) {
        Intent intent = new Intent(context, HttpService.class);
        intent.setAction(HttpConstants.ACTION_SIGNUP);
        intent.putExtra(HttpConstants.EXTRA_PARAM1, loginname);
        intent.putExtra(HttpConstants.EXTRA_PARAM2, password);
        intent.putExtra(HttpConstants.EXTRA_PARAM3, pos);
        context.startService(intent);
    }

    public static void startServiceUserList(Context context, Long managerId) {
        Intent intent = new Intent(context, HttpService.class);
        intent.setAction(HttpConstants.ACTION_USERLIST);
        intent.putExtra(HttpConstants.EXTRA_PARAM1, managerId);
        context.startService(intent);
    }

    public static void startServiceDrivingRecord(Context context, String driverId,Date start,Date end,Integer type) {
        Intent intent = new Intent(context, HttpService.class);
        intent.setAction(HttpConstants.ACTION_DRIVINGRECORD);
        intent.putExtra(HttpConstants.EXTRA_PARAM1, driverId);
        intent.putExtra(HttpConstants.EXTRA_PARAM2, start);
        intent.putExtra(HttpConstants.EXTRA_PARAM3, end);
        intent.putExtra(HttpConstants.EXTRA_PARAM4, type);
        context.startService(intent);
    }

    public static void startServiceEvaluation(Context context, Long id, Integer type) {
        Intent intent = new Intent(context, HttpService.class);
        intent.setAction(HttpConstants.ACTION_EVALUATION);
        intent.putExtra(HttpConstants.EXTRA_PARAM1, id);
        intent.putExtra(HttpConstants.EXTRA_PARAM2, type);
        context.startService(intent);
    }

    public static void startServiceEvaluationByUserList(Context context, ArrayList<User> users, Integer type) {
        LogUtil.d(TAG, "startServiceEvaluationByUserList() ");
        Intent intent = new Intent(context, HttpService.class);
        intent.setAction(HttpConstants.ACTION_EVALUATIONBYUSERLIST);
        intent.putParcelableArrayListExtra(HttpConstants.EXTRA_PARAM1, users);
        intent.putExtra(HttpConstants.EXTRA_PARAM2, type);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            switch (action) {
                case HttpConstants.ACTION_LOGIN: {
                    final String loginname = intent.getStringExtra(HttpConstants.EXTRA_PARAM1);
                    final String password = intent.getStringExtra(HttpConstants.EXTRA_PARAM2);
                    final boolean isManager = intent.getBooleanExtra(HttpConstants.EXTRA_PARAM3, false);
                    handleActionLogin(loginname, password, isManager);
                    break;
                }case HttpConstants.ACTION_SIGNUP: {
                    final String loginname = intent.getStringExtra(HttpConstants.EXTRA_PARAM1);
                    final String password = intent.getStringExtra(HttpConstants.EXTRA_PARAM2);
                    final Integer job= intent.getIntExtra(HttpConstants.EXTRA_PARAM3,0);
                    handleActionSignUp(loginname, password, job);
                    break;
                }
                case HttpConstants.ACTION_USERLIST: {
                    final Long managerId = intent.getLongExtra(HttpConstants.EXTRA_PARAM1, -1);
                    handleActionUserList(managerId);
                    break;
                }
                case HttpConstants.ACTION_DRIVINGRECORD: {
                    final String driverId = intent.getStringExtra(HttpConstants.EXTRA_PARAM1);
                    final Date start = (Date) intent.getSerializableExtra(HttpConstants.EXTRA_PARAM2);
                    final Date end = (Date) intent.getSerializableExtra(HttpConstants.EXTRA_PARAM3);
                    final Integer type = intent.getIntExtra(HttpConstants.EXTRA_PARAM4,0);
                    handleActionDrivingRecord(driverId,start,end,type);
                    break;
                }
                case HttpConstants.ACTION_EVALUATION: {
                    final Long userId = intent.getLongExtra(HttpConstants.EXTRA_PARAM1, -1);
                    final Integer type = intent.getIntExtra(HttpConstants.EXTRA_PARAM2, -1);
                    handleActionEvaluation(userId, type);
                    break;
                }
                case HttpConstants.ACTION_EVALUATIONBYUSERLIST: {
                    final List<User> users = intent.getParcelableArrayListExtra(HttpConstants.EXTRA_PARAM1);
                    final Integer type = intent.getIntExtra(HttpConstants.EXTRA_PARAM2, -1);
                    handleActionEvaluationByUserList(users, type);
                    break;
                }
                case HttpConstants.ACTION_OILBYDAY: {
                    final Date date = (Date) intent.getSerializableExtra(HttpConstants.EXTRA_PARAM1);
                    break;
                }
                default:
                    break;
            }
        }
    }

    private void handleActionSignUp(String loginname, String password, Integer job) {
        Log.d(TAG, "handleActionSignUp() called with: loginname = [" + loginname + "], password = [" + password + "], job = [" + job + "]");
        NetMsg netMsg = new NetMsg(NetMsg.BACKGROUND, HttpConstants.ACTION_SIGNUP);
        User user = HttpManager.userSignUp(loginname, password, job);
        if (user != null) {
            Long id = BeanServer.getInstance().saveUser(user);
            netMsg.setRESULT(HttpConstants.RESULT_OK);
            netMsg.setId(id);
        } else {
            String errMsg = HttpManager.getErrorCode() + ":" + HttpManager.getErrorMsg();
            netMsg.setRESULT(HttpConstants.RESULT_ERR);
            netMsg.setERR_MSG(errMsg);
        }
        EventBus.getDefault().post(netMsg);
    }


    private void handleActionUserList(Long managerId) {
        NetMsg netMsg = new NetMsg(NetMsg.BACKGROUND, HttpConstants.ACTION_USERLIST);
        List<User> users = null;
        try {
            users = HttpManager.getUserList(managerId);
            if (users != null) {
                if (users.size() > 0) {
                    long count = BeanServer.getInstance().saveUserList(users);
                    netMsg.setRESULT(HttpConstants.RESULT_OK);
                    netMsg.setCount(count);
                } else {
                    netMsg.setRESULT(HttpConstants.RESULT_ERR);
                    netMsg.setERR_MSG("列表为空");
                }
            } else {
                String errMsg = HttpManager.getErrorCode() + ":" + HttpManager.getErrorMsg();
                netMsg.setRESULT(HttpConstants.RESULT_ERR);
                netMsg.setERR_MSG(errMsg);
            }
        } catch (IOException e) {
            netMsg.setRESULT(HttpConstants.RESULT_ERR);
            netMsg.setERR_MSG(e.getMessage());
        }

        EventBus.getDefault().post(netMsg);
    }

    private void handleActionEvaluation(Long userId, Integer type) {
        LogUtil.d(TAG, "handleActionEvaluation() called with: userId = [" + userId + "], type = [" + type + "]");
        NetMsg netMsg = new NetMsg(NetMsg.BACKGROUND, HttpConstants.ACTION_EVALUATION);
        if (userId > 0 && type > 0) {
            List<Evaluation> evaluations = HttpManager.getEvaluations(userId, type);
            Log.d(TAG, "handleActionEvaluation: evaluation size=" + evaluations.size());
            if (evaluations != null) {
                Long count = BeanServer.getInstance().saveEvaluations(evaluations);
                netMsg.setRESULT(HttpConstants.RESULT_OK);
                netMsg.setCount(count);
            } else {
                String errMsg = HttpManager.getErrorCode() + ":" + HttpManager.getErrorMsg();
                netMsg.setRESULT(HttpConstants.RESULT_ERR);
                netMsg.setERR_MSG(errMsg);
            }
        } else {
            String errMsg = "参数有误";
            netMsg.setRESULT(HttpConstants.RESULT_ERR);
            netMsg.setERR_MSG(errMsg);
        }

        EventBus.getDefault().post(netMsg);
    }

    private void handleActionEvaluationByUserList(List<User> users, Integer type) {
        Log.d(TAG, "handleActionEvaluationByUserList() ");
        NetMsg netMsg = new NetMsg(NetMsg.BACKGROUND, HttpConstants.ACTION_EVALUATIONBYUSERLIST);
        if (type > 0) {
            List<Evaluation> evaluations = HttpManager.getEvaluationsByUserList(users, type);
            Log.d(TAG, "handleActionEvaluation: evaluation size=" + evaluations.size());
            if (evaluations != null) {
                Long count = BeanServer.getInstance().saveEvaluations(evaluations);
                netMsg.setRESULT(HttpConstants.RESULT_OK);
                netMsg.setCount(count);
            } else {
                String errMsg = HttpManager.getErrorCode() + ":" + HttpManager.getErrorMsg();
                netMsg.setRESULT(HttpConstants.RESULT_ERR);
                netMsg.setERR_MSG(errMsg);
            }
        } else {
            String errMsg = "参数有误";
            netMsg.setRESULT(HttpConstants.RESULT_ERR);
            netMsg.setERR_MSG(errMsg);
        }
        EventBus.getDefault().post(netMsg);
    }



    private void handleActionDrivingRecord(String driverId,Date start,Date end,Integer type) {
        NetMsg netMsg = new NetMsg(NetMsg.BACKGROUND, HttpConstants.ACTION_DRIVINGRECORD);

        if (0==type){
            try {
                DayData dayData = HttpManager.getDriverDataByDateRange(driverId,start,end);
                if (dayData!=null){
                    int count = ResolveNetData.resolveDateData(dayData,driverId);
                    netMsg.setRESULT(HttpConstants.RESULT_OK);
                    netMsg.setCount((long)count);
                }else {
                    String errMsg = HttpManager.getErrorCode() + ":" + HttpManager.getErrorMsg();
                    netMsg.setRESULT(HttpConstants.RESULT_ERR);
                    netMsg.setERR_MSG(errMsg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                netMsg.setRESULT(HttpConstants.RESULT_ERR);
                netMsg.setERR_MSG(e.getMessage());
            }
        }else if (1==type){
            try {
                MonthData monthData = HttpManager.getDriverDataByMonthRange(driverId,start,end);
                if (monthData!=null){
                    int count = ResolveNetData.resolveMonthData(monthData,driverId);
                    netMsg.setRESULT(HttpConstants.RESULT_OK);
                    netMsg.setCount((long)count);
                }else {
                    String errMsg = HttpManager.getErrorCode() + ":" + HttpManager.getErrorMsg();
                    netMsg.setRESULT(HttpConstants.RESULT_ERR);
                    netMsg.setERR_MSG(errMsg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                netMsg.setRESULT(HttpConstants.RESULT_ERR);
                netMsg.setERR_MSG(e.getMessage());
            }
        }
        EventBus.getDefault().post(netMsg);
    }

    /**
     * 处理登录请求
     *
     * @param loginname
     * @param password
     * @param isManager
     */
    private void handleActionLogin(String loginname, String password, boolean isManager) {
        Log.d(TAG, "handleActionLogin() called with: loginname = [" + loginname + "], password = [" + password + "], isManager = [" + isManager + "]");
        NetMsg netMsg = new NetMsg(NetMsg.BACKGROUND, HttpConstants.ACTION_LOGIN);
        User user = HttpManager.userLogin(loginname, password, isManager);
        if (user != null) {
            Long id = BeanServer.getInstance().saveUser(user);
            netMsg.setRESULT(HttpConstants.RESULT_OK);
            netMsg.setId(id);
        } else {
            String errMsg = HttpManager.getErrorCode() + ":" + HttpManager.getErrorMsg();
            netMsg.setRESULT(HttpConstants.RESULT_ERR);
            netMsg.setERR_MSG(errMsg);
        }
        EventBus.getDefault().post(netMsg);
    }


}
